package com.dragon.mmochat.service;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dragon.mmochat.MmochatConstant;
import com.dragon.mmochat.MmochatMain;
import com.dragon.mmochat.message.Mmochat_ClientVersionError;
import com.dragon.mmochat.message.Mmochat_ServerStateMessage;
import com.dragon.mmochat.model.enumType.MmochatServerStateType;
import com.dragon.mmochat.model.object.MmochatPackageGrid;
import com.dragon.mmochat.model.role.MmochatPlayer;
import com.dragon.mmochat.util.MmochatUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.skymobi.buffer.Charset;
import com.skymobi.buffer.SkymobiBuffer;
import com.skymobi.message.SkymobiProtocolMessage.UserConnInfo;

public class MmochatManageService {
	private static Logger log = LoggerFactory
			.getLogger(MmochatManageService.class);

	private ScheduledExecutorService connectThread = Executors
			.newScheduledThreadPool(1);
	private static Socket socket = null;
	private static final int timeoutTime = 20;
	private static final String hostName = "127.0.0.1";// "qinlonggame.cn";

	// 协议号
	private static final int MSGCODE_MMOCHAT_MANAGE_BASE = 0x1227; // 总协议号
	private static final int MSGCODE_MMOCHAT_MANAGE_1_1C = 1; // 发送：全服聊天消息

	public MmochatManageService() {
//		log.debug("MmochatManageService create");

//		connectThread.scheduleWithFixedDelay(new ConnectToServer(), 5, 30,
//				TimeUnit.SECONDS);

	}

	/******************************* socket连接管理 *********************************/

	class ConnectToServer implements Runnable {
		@Override
		public void run() {
			try {
				if (socket != null && !socket.isClosed()
						&& socket.isConnected()) {
					// socket已连接
					return;
				}
				
				if (socket == null || socket.isClosed()) {
					socket = new Socket();
					log.debug("创建新的socket");
				}

				InetAddress addr = InetAddress.getByName(hostName);
				InetSocketAddress serverAddress = new InetSocketAddress(addr,
						MmochatConstant.chatServerPort);
				try {
					log.debug("socket连接中...");
					socket.connect(serverAddress, timeoutTime * 1000);
					// 已连接
					if (socket.isConnected()) {
						log.error("聊天服务端socket已连接!");
					}
					new CheckSocket(socket).start();

				} catch (IOException e) {
					closeSocket(socket);
					socket = null;
				} catch (Exception e) {
					closeSocket(socket);
					socket = null;
				}

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private static void closeSocket(Socket s) {
		if (s != null && !s.isClosed()) {
			try {
				s.close();
				log.error("聊天服务器socket已断开!");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	// 检查socket是否断开
	public class CheckSocket extends Thread {
		Socket mySocket;

		public CheckSocket(Socket socket) {
			this.mySocket = socket;
		}

		public void run() {
			while (true) {
				try {
					mySocket.sendUrgentData(0);
					Thread.sleep(10000);
				} catch (Exception e) {
					closeSocket(mySocket);
					break;
				}
			}
		}
	}

	/******************************** 游戏逻辑 ********************************/
	// 协议格式:msgcode+0(int)+len+data, len包含本身4个字节和前面8个字节

	// 发送全服聊天消息
	/*
	public static void sendWorldChatToAll(List<Mmochat_11_2SData> msgList) {
		if (msgList == null || msgList.size() == 0) {
			return;
		}
		if (socket != null && !socket.isClosed() && socket.isConnected()) {
			// socket已连接

			try {
				log.debug("收到聊天消息，准备打包");
				ByteArrayOutputStream outStr = new ByteArrayOutputStream();
				ObjectOutputStream oo = new ObjectOutputStream(outStr);
				oo.writeObject(msgList);
				byte[] outData = outStr.toByteArray();

				// 发送
				int len = 12 + 4 + 4 + 4 + 4 + outData.length;
				OutputStream out = socket.getOutputStream();
				SkymobiBuffer data = SkymobiBuffer.allocate(len);

				data.putInt(MSGCODE_MMOCHAT_MANAGE_BASE);
				data.putInt(0);
				// 消息总长度
				data.putInt(len);
				// 协议号
				data.putInt(MSGCODE_MMOCHAT_MANAGE_1_1C);
				data.putInt(MmochatMain.getModuleInstID());
				data.putInt(MmochatConstant.getClientModuleId());
				// msg长度
				data.putInt(outData.length);
				// msg数据
				data.put(outData);

				log.debug("打包完成，准备发送，len="+len);
				// 发送
				out.write(data.arrayToPosition());
				log.debug("消息发送到聊天服务器!");
			} catch (IOException e) {
				e.printStackTrace();
			}

		}

	}*/

}
